<template>
  <div class="entries-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <h2 class="page-title">词条管理</h2>
      <div class="action-buttons">
        <el-button type="danger" @click="delSelected" icon="Delete" size="large">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 词条表格 -->
    <div class="table-card">
      <el-table
          ref="tableRef"
          :data="data.tableData"
          stripe
          border
          v-loading="data.loading"
          style="width: 100%"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column label="词条ID" prop="entryId" width="100" align="center"></el-table-column>
        <el-table-column label="词条名称" prop="entryName" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column label="来源" prop="source" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="分类" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.categories?.categoryName" type="info" size="small">
              {{ scope.row.categories.categoryName }}
            </el-tag>
            <span v-else class="empty-text">未分类</span>
          </template>
        </el-table-column>
        <el-table-column label="发布人" width="120" align="center">
          <template #default="scope">
            <div class="user-info">
              <span v-if="scope.row.user?.username">{{ scope.row.user.username }}</span>
              <span v-else class="empty-text">未知用户</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="130" align="center">
          <template #default="scope">
            <el-select
                v-model="scope.row.status"
                size="small"
                @change="handleStatusChange(scope.row)"
                :class="`status-${scope.row.status}`"
            >
              <el-option label="待定" value="pending"></el-option>
              <el-option label="通过" value="approved"></el-option>
              <el-option label="不通过" value="rejected"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="140" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button
                type="danger"
                circle
                size="small"
                @click="del(scope.row.entryId)"
                icon="Delete"
                title="删除词条"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
            background
            :total="data.total"
            :current-page="data.page"
            :page-size="data.limit"
            @current-change="jump"
            layout="total, prev, pager, next, jumper"
            :page-sizes="[5, 10, 20, 50]"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import axios from "@/utils/axios.js";
import { ElMessage, ElMessageBox } from 'element-plus';

const tableRef = ref();
const data = reactive({
  tableData: [],
  page: 1,
  limit: 10,
  total: 0,
  loading: false,
  selectedEntries: []
});

// 初始化数据
const init = () => {
  data.loading = true;
  const url = `/api/epage?page=${data.page}&limit=${data.limit}`;

  axios.post(url)
      .then(res => {
        console.log("响应数据：", res);
        data.tableData = res.records;
        data.total = res.total;
      })
      .catch(error => {
        console.error("获取数据失败：", error);
        ElMessage.error("获取数据失败");
      })
      .finally(() => {
        data.loading = false;
      });
};

// 分页跳转
const jump = (val) => {
  data.page = val;
  init();
};

// 改变每页显示数量
const handleSizeChange = (val) => {
  data.limit = val;
  data.page = 1;
  init();
};

// 选择改变
const handleSelectionChange = (selection) => {
  data.selectedEntries = selection;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 状态改变
const handleStatusChange = (row) => {
  axios.post("/api/updateStatus", null, {
    params: {
      entryId: row.entryId,
      status: row.status
    }
  }).then(res => {
    ElMessage({
      message: "状态更新成功",
      type: "success",
      duration: 1000
    });
  }).catch(error => {
    console.error("状态更新失败：", error);
    ElMessage.error("状态更新失败");
    // 重新加载数据以恢复原状态
    init();
  });
};

// 删除单个词条
const del = (entryId) => {
  ElMessageBox.confirm(
      '确定要删除这个词条吗？此操作不可恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    axios.get(`/api/removeByEid?entryId=${entryId}`)
        .then(res => {
          ElMessage({
            message: "删除成功",
            type: "success",
            duration: 1000,
            onClose: () => {
              init();
            }
          });
        })
        .catch(error => {
          console.error("删除失败：", error);
          ElMessage.error("删除失败");
        });
  }).catch(() => {
    // 用户取消删除
  });
};

// 批量删除
const delSelected = () => {
  if (data.selectedEntries.length === 0) {
    ElMessage.warning("请先选择要删除的词条");
    return;
  }

  const entryIds = data.selectedEntries.map(row => row.entryId);

  ElMessageBox.confirm(
      `确定要删除选中的 ${entryIds.length} 个词条吗？此操作不可恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    axios.post("/api/removeByEids", entryIds)
        .then(res => {
          ElMessage({
            message: `成功删除 ${entryIds.length} 个词条`,
            type: "success",
            duration: 1500,
            onClose: () => {
              init();
            }
          });
        })
        .catch(error => {
          console.error("批量删除失败：", error);
          ElMessage.error("批量删除失败");
        });
  }).catch(() => {
    // 用户取消删除
  });
};

onMounted(() => {
  init();
});
</script>

<style scoped>
.entries-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.table-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.empty-text {
  color: #c0c4cc;
  font-style: italic;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.status-pending) .el-input__inner {
  color: #e6a23c;
  font-weight: 500;
}

:deep(.status-approved) .el-input__inner {
  color: #67c23a;
  font-weight: 500;
}

:deep(.status-rejected) .el-input__inner {
  color: #f56c6c;
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-table .el-tag) {
  border: none;
  padding: 4px 8px;
}
</style>